﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;

namespace WPF_MVVMDemo
{
    /// <summary>
    /// 默认选中第一个的 ComboBox
    /// </summary>
    public class CustomComboBox : ComboBox
    {
        public CustomComboBox()
        {
            Loaded += new System.Windows.RoutedEventHandler(CustomComboBox_Loaded);
            SelectionChanged += new SelectionChangedEventHandler(CustomComboBox_SelectionChanged);
        }

        void CustomComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SelectedItem = e.AddedItems.Count > 0 ? e.AddedItems[0] : null;
        }

        void CustomComboBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            SetSelectedItem();
        }
        private void SetSelectedItem()
        {
            if (Items.Count > 0)
                base.SelectedIndex = 0;//默认选中第一
        }
        protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            base.OnItemsChanged(e);
            SetSelectedItem();
        }
        public new static readonly DependencyProperty SelectedItemProperty =
            DependencyProperty.Register("SelectedItem", typeof(object), typeof(CustomComboBox),
            new PropertyMetadata((o, e) => ((CustomComboBox)o).SetSelectedItem()));
    }
}
